<template>
	<div id="map-container" style="width: 100%; height: 760px;">
		<ul class="search-result">
			<li v-for="item in result" :key="item.id">
				<span @click="resultSearch(item)">{{item.name}}</span>
			</li>
		</ul>
		<div class="form-info">
			<el-form :model="form" ref="form" :rules="rules" size="small" label-width="70px">
				<el-row>
					<el-col :span="11">
						<el-form-item prop="addLon" label="经度">
							<el-input v-model="form.addLon" :maxlength="15" placeholder="请输入经度"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item prop="addLat" label="纬度">
							<el-input v-model="form.addLat" :maxlength="15" placeholder="请输入纬度"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="2">
						<el-button type="primary" class="button" size="mini" @click="updateAddress(Number(form.addLon),Number(form.addLat))">定位</el-button>
					</el-col>
				</el-row>
			</el-form>
		</div>
		<div class="container">
			<template v-if="isCustom">
				<div class="search-box">
					<el-input v-model="searchKey" type="search" id="search" placeholder="请输入详细地址"></el-input>
					<el-button type="primary" class="button" size="mini" @click="searchByHand">搜索</el-button>
					<div class="tip-box" id="searchTip"></div>
				</div>
			</template>
			<template v-else>
				<el-amap-search-box class="search-box" ref="searchBox"
					:events="events"
					:search-option="searchOption"
					:on-search-result="onSearchResult">
				</el-amap-search-box>
			</template>
			<el-amap class="amap-box" vid="amap-vue"
				:zoom="zoom"
				:plugin="plugins"
				:center="center"
				:events="events"
				:amap-manager="amapManager">
				<!-- 标记 -->
				<el-amap-marker v-for="(marker, index) in markers" :key="'marker' + index"
					:events="marker.events"
					:position="marker.position">
				</el-amap-marker>
				<!--构造矢量圆形 AMap.Circle({
					center: new AMap.LngLat("116.403322", "39.920255"), // 圆心位置
					radius: 1000,  //半径
					strokeColor: "#F33",  //线颜色
					strokeOpacity: 1,  //线透明度
					strokeWeight: 3,  //线粗细度
					fillColor: "#ee2200",  //填充颜色
					fillOpacity: 0.35 //填充透明度
				})-->
				<el-amap-circle vid="circle" fill-opacity="0.2" strokeColor="#38f" strokeOpacity="0.8" strokeWeight="1" fillColor="#38f"
					:center="center"
					:radius="circleRadius">
				</el-amap-circle>
			</el-amap>
		</div>
	</div>
</template>
<script>
import {AMapManager, lazyAMapApiLoaderInstance} from "vue-amap";
import VAmap from "utils/VAmap.js";

let amapManager = new AMapManager();
export default {
	name: "base-map",
	props: {
		city: {
			type: String,
			defatult: ""
		},
		longitude: {
			type: String,
			defatult: ""
		},
		latitude: {
			type: String,
			defatult: ""
		},
		isCustom: {
			type: Boolean,
			default: false
		}
	},
	data() {
		let self = this;
		return {
			zoom: 14,
			lng: 0,
			lat: 0,
			loaded: false,
			radius: 10,
			circleRadius: 500,
			address: "",
			searchKey: "",
			result: [],
			markers: [],
			map: null,
			geocoder: null,
			geolocation: null,
			poiPicker: null,
			amapManager,
			searchOption: {
				city: self.city ? self.city : "全国",
				citylimit: true
			},
			center: [120.183227, 30.243274], // 地图初始化视图中心点
			form: {
				addLon: "120.183227",
				addLat: "30.243274"
			},
			rules: {
				addLat: [
					{
						required: true,
						message: "请输入纬度",
						trigger: ["blur", "change"]
					}
				],
				addLon: [
					{
						required: true,
						message: "请输入经度",
						trigger: ["blur", "change"]
					}
				]
			},
			events: {
				init(instance) {
					console.log("地图实例", instance);
					lazyAMapApiLoaderInstance.load().then(() => {
						if (instance.CLASS_NAME === "AMap.Map") {
							self.initMap(instance);
						}
						if (self.isCustom) {
							self.initSearch(instance);
						}
					});
				},
				// 点击获取地址的数据
				click(e) {
					self.result = [];
					self.$refs.searchBox.keyword = "";
					self.$refs.searchBox.tips = [];
					let {lng, lat} = e.lnglat;
					self.updateAddress(lng, lat);
				}
			},
			// 一些工具插件
			plugins: VAmap.initPlugins(self)// 这里放扩展的插件
		};
	},
	created() {
		this.vueAmap.init();
		this.initData();
	},
	methods: {
		initMap(instance) {
			this.map = instance ? instance : amapManager.getMap();
		},
		initData() {
			if (this.longitude && this.latitude) {
				this.setData(this.longitude, this.latitude);
			} else {
				this.getLocation(null);
			}
		},
		setData(longitude, latitude) {
			this.zoom = 16;
			this.loaded = true;
			this.circleRadius = 100;
			this.form.addLon = longitude;
			this.form.addLat = latitude;
			this.lng = Number(longitude);
			this.lat = Number(latitude);
			this.center = [Number(longitude), Number(latitude)];
			this.markers.push({
				events: this.events,
				postiton: [Number(longitude), Number(latitude)]
			});
			this.$nextTick();
		},
		convertGps(gps) {
			let lnglats = [];
			AMap.convertFrom(gps, "gps", (status, result) => {
				if (result.info === "ok") {
					lnglats = result.locations; // Array.<LngLat>
				}
			});
			return lnglats;
		},
		onSearchResult(pois) {
			let latSum = 0;
			let lngSum = 0;
			this.result = pois;
			if (pois.length > 0) {
				let point = {}, center = {};
				pois.forEach(poi => {
					if (poi.name === this.$refs.searchBox.keyword) {
						point = poi;
					} else {
						let {lng, lat} = poi;
						lngSum += lng;
						latSum += lat;
					}
				});
				console.log("keyword", this.$refs.searchBox.keyword);
				console.log("poi ", point);
				if (point) {
					let {lng, lat} = point;
					center = {
						lng: lng,
						lat: lat
					};
				} else {
					center = {
						lng: lngSum / pois.length,
						lat: latSum / pois.length
					};
				}
				this.setData(center.lng, center.lat);
				console.log("center", this.center);
			}
		},
		startDrag() {
			AMapUI.loadUI(["misc/PositionPicker"], (PositionPicker) => {
				let positionPicker = new PositionPicker({
					mode: "dragMap",
					map: this.map
				});
				//定位
				this.getLocation(positionPicker);
				positionPicker.on("success", (positionResult) => {
					console.log("定位结果", positionResult);
					this.result = positionResult.regeocode.pois;
					this.address = positionResult.regeocode.formattedAddress;
					this.setData(positionResult.position.lng, positionResult.position.lat);
					positionPicker.stop();
				});
				positionPicker.on("fail", (failResult) => {
					console.log(failResult);
				});
			});
		},
		updateAddress(longitude, latitude) {
			this.center = [];
			this.markers = [];
			this.geocoder.getAddress([Number(longitude), Number(latitude)], (status, result) => {
				if (status === "complete" && result.info === "OK") {
					if (result && result.regeocode) {
						console.log("address", result.regeocode.formattedAddress); //控制台打印地址
						this.address = result.regeocode.formattedAddress;
						if (this.isCustom) {
							this.searchKey = result.regeocode.formattedAddress;
						}
					}
				}
			});
			this.setData(longitude, latitude);
		},
		searchByHand() {
			if (this.searchKey !== "" && this.poiPicker) {
				this.poiPicker.searchByKeyword(this.searchKey);
			}
		},
		resultSearch(tip) {
			if (this.isCustom) {
				this.searchKey = tip.name;
				this.searchByHand();
			} else {
				this.$refs.searchBox.changeTip(tip);
			}
		},
		getLocation(positionPicker) {
			if (!this.map) {
				this.center = [120.183227, 30.243274];// 地图初始化视图中心点
				this.form = {
					addLon: "120.183227",
					addLat: "30.243274"
				};
				return;
			}
			AMap.plugin("AMap.Geolocation", () => {
				this.map.addControl(this.geolocation);
				this.geolocation.getCurrentPosition();
				AMap.event.addListener(this.geolocation, "complete", (data) => {
					console.log("定位信息", data);// data是具体的定位信息
					if (positionPicker) {
						positionPicker.start();
					} else {
						this.result = data.pois;
						this.address = data.formattedAddress;
						let longitude = data.position.lng;
						let latitude = data.position.lat;
						this.setData(longitude, latitude);
						console.log("center", this.center);
						console.log("address", this.address);
					}
				});
				AMap.event.addListener(this.geolocation, "error", (data) => {
					// 失败 启用 ip定位
					AMap.plugin("AMap.CitySearch", () => {
						let citySearch = new AMap.CitySearch();
						citySearch.getLocalCity((status, result) => {
							if (status === "complete" && result.info === "OK") {
								// 查询成功，result即为当前所在城市信息
								console.log("通过ip获取当前城市：", result);
							}
						});
					});
				});
			});
		},
		getWeather(district) {
			//加载天气查询插件
			AMap.plugin("AMap.Weather", () => {
				//创建天气查询实例
				let weather = new AMap.Weather();

				//执行实时天气信息查询
				weather.getLive(district, (err, data) => {
					console.log(err, data);
				});
				//执行实时天气信息查询
				weather.getForecast(district, (err, data) => {
					console.log(err, data);
				});

			});
		},
		getDrivingPolicy(lngLats, points, waypoints) {
			AMap.plugin("AMap.Driving", () => {
				let driving = new AMap.Driving({
					// 驾车路线规划策略，AMap.DrivingPolicy.LEAST_TIME是最快捷模式
					policy: AMap.DrivingPolicy.LEAST_TIME,
					// map 指定将路线规划方案绘制到对应的AMap.Map对象上
					map: this.map,
					// panel 指定将结构化的路线详情数据显示的对应的DOM上，传入值需是DOM的ID
					panel: "panel"
				});
				if (lngLats) {
					lngLats = {
						startLngLat: [116.379028, 39.865042],
						endLngLat: [116.427281, 39.903719]
					};
					driving.search(lngLats.startLngLat, lngLats.endLngLat, (status, result) => {
						// 未出错时，result即是对应的路线规划方案
					});
				} else if (points) {
					let pointsArray = [
						{keyword: "北京市地震局（公交站）", city: "北京"},
						{keyword: "亦庄文化园（地铁站）", city: "北京"}
					];
					if (waypoints) {
						let opts = {
							waypoints: [// 途经点参数，最多支持传入16个途经点
								{keyword: "北京站", city: "北京"}
							]
						};
						driving.search(pointsArray, opts, (status, result) => {
							// 未出错时，result即是对应的路线规划方案
						});
					} else {
						driving.search(pointsArray, (status, result) => {
							// 未出错时，result即是对应的路线规划方案
						});
					}
					// 搜索完成后，将自动绘制路线到地图上
					driving.search(pointsArray);
				}
			});
		},
		initSearch(instance) {
			this.map = this.amapManager.getMap();
			AMapUI.loadUI(["misc/PoiPicker"], (PoiPicker) => {
				let poiPicker = new PoiPicker({
					input: "search",
					placeSearchOptions: {
						map: this.map ? this.map : instance,
						pageSize: 10
					},
					suggestContainer: "searchTip",
					searchResultsContainer: "searchTip"
				});
				this.poiPicker = poiPicker;
				// 监听poi选中信息
				poiPicker.on("poiPicked", (poiResult) => {
					// console.log(poiResult)
					let source = poiResult.source;
					let poi = poiResult.item;
					if (source !== "search") {
						poiPicker.searchByKeyword(poi.name);
					} else {
						poiPicker.clearSearchResults();
						this.markers = [];
						let lng = poi.location.lng;
						let lat = poi.location.lat;
						let address = poi.cityname + poi.adname + poi.name;
						if (this.isCustom) {
							this.searchKey = address;
						}
						this.address = address;
						this.setData(lng, lat);
					}
				});
			});
		}
	},
	destroyed() {
		if (this.map != null) {
			this.map.destroy();
		}
	},
	watch: {
		map() {
			if (this.map != null) {
				this.startDrag();
			}
		}
	}
};
</script>
<style scoped>
.container {
	width: 100%;
	height: 100%;
	position: relative;
	left: 50%;
	top: 50%;
	transform: translate3d(-50%, -50%, 0);
	border: 1px solid #999999;
}

.search-box {
	position: absolute;
	z-index: 5;
	width: 25%;
	right: 6%;
	top: 10px;
	height: 30px;
	border: 1px solid grey;
}

.search-result {
	position: absolute;
	text-align: left;
	font-size: 14px;
	z-index: 5;
	width: 15%;
	left: 5%;
	top: -5px;
	line-height: 20px;
	background-color: #BBCBEE;
	border: 1px solid #EAE3E3;
}

.search-result :hover {
	cursor: pointer;
	color: #0977EA;
}

.form-info {
	position: absolute;
	text-align: left;
	font-size: 14px;
	z-index: 5;
	width: 40%;
	left: 25%;
	top: 10px;
	height: 30px;
	background-color: #BBCBEE;
	border: 1px solid grey;
}

.search-box input {
	float: left;
	width: 80%;
	height: 100%;
	border: 1px solid #30CCC1;
	padding: 0 8px;
	outline: none;
}

.search-box button {
	float: left;
	width: 20%;
	height: 100%;
	background: #30CCC1;
	border: 1px solid #30CCC1;
	color: #FFFFFF;
	outline: none;
}

.tip-box {
	width: 100%;
	max-height: 260px;
	position: absolute;
	top: 30px;
	overflow-y: auto;
	background-color: #FFFFFF;
}

.amap-box {
	width: 100%;
	height: 100%;
	position: relative;
	left: 50%;
	top: 50%;
	transform: translate3d(-50%, -50%, 0);
	border: 1px solid #999999;
}

.button {
	padding-top: 8px;
	padding-bottom: 8px;
}

hr {
	border-color: red;
	border-style: dashed;
}
</style>
